package com.lzy.wzy.netty.handler;


import com.lzy.wzy.netty.msg.PublicRequestMessage;
import com.lzy.wzy.utils.BusinessUtils;
import com.lzy.wzy.utils.JsonUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
@ChannelHandler.Sharable
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    @Autowired
    private BusinessUtils businessUtils;

    @Autowired
    private ExecutorHandler executorHandler;

    @Autowired
    private JsonUtil jsonUtil;


    @Override
    public void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String msg = textWebSocketFrame.text();
        log.info("data msg{}", msg);
        PublicRequestMessage requestMessage = jsonUtil.jsonToPojo(msg, PublicRequestMessage.class);
        executorHandler.execute(requestMessage,channelHandlerContext,msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        businessUtils.doExecute(ctx.channel());
        ctx.close();
    }


}
